package main

import (
	"net/http"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
	"flag"
	"encoding/json"
)

const (
	defaultfile = "1"
)

var port = flag.Int("p", 12888, "-p=12888")
var nossl = flag.Bool("nossl", false, "-nossl")
var combine = flag.Bool("combine", false, "-combine");

type BuildingPos struct {
	Positionx float32 `json:positionx`
	Positiony float32 `json:positiony`
	Positionz float32 `json:positionz`
	Rotationx float32 `json:rotationx`
	Rotationy float32 `json:rotationy`
	Rotationz float32 `json:rotationz`
}
func main() {
	flag.Parse()

	// 将本文件夹的内容打包成一个json

	if *combine {

		var buildings map[string]BuildingPos = make(map[string]BuildingPos)

		files, _ := ioutil.ReadDir("./");
		for _, f := range files {
			if f.IsDir() {
				continue
			}

			if f.Name() == "pos.json" {
				continue
			}

			if f.Name() == "1.json" {
				continue
			}

			data, err := ioutil.ReadFile(f.Name())
			if err == nil {
				var building = BuildingPos{};
				json.Unmarshal(data, &building)
				buildings[f.Name()] = building
				fmt.Println("加载文件：", f.Name(), building.Positionx)
			}
		}

		// 保存json
		{
			data, err := json.Marshal(buildings)
			if err == nil {

				var content = string(data);
				content = strings.Replace(content, "Positionx", "positionx", -1)
				content = strings.Replace(content, "Positiony", "positiony", -1)
				content = strings.Replace(content, "Positionz", "positionz", -1)
				content = strings.Replace(content, "Rotationx", "rotationx", -1)
				content = strings.Replace(content, "Rotationy", "rotationy", -1)
				content = strings.Replace(content, "Rotationz", "rotationz", -1)

				ioutil.WriteFile("pos.json", []byte(content), os.ModePerm)
				fmt.Println("合并位置信息成功")
			}
		}

		return
	}

	http.HandleFunc("/ajaxinfo", ajaxInfo)
	http.HandleFunc("/savejson", saveJson)
	http.HandleFunc("/hello", HelloServer)

	var addr = fmt.Sprintf(":%d", *port)
	fmt.Println("start... addr=", addr, *port, *nossl)

	var err error = nil
	if *nossl {
		err = http.ListenAndServe(addr, nil) //设置监听的端口

	} else {
		err = http.ListenAndServeTLS(addr, "server.crt", "server.key", nil) //设置监听的端口
	}
	if err != nil {
		fmt.Println("ListenAndServe: ", err)
	}
	fmt.Println("end...")
}
func HelloServer(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte("This is an example server.\n"))
	// fmt.Fprintf(w, "This is an example server.\n")
	// io.WriteString(w, "This is an example server.\n")
}
func ajaxInfo(w http.ResponseWriter, r *http.Request) {

	fmt.Println("wx path", strings.Join([]string{"http://", r.Host, r.RequestURI}, ""))

	r.ParseForm()

	w.Header().Set("Content-type", "application/json")

	filename := defaultfile;
	if len(r.Form["file"]) > 0 {
		filename = 	r.Form["file"][0]
	}
	fmt.Println("filename:", filename)

	data, err := ioutil.ReadFile(filename + ".json")
	if err != nil {
		data = []byte("{}")
	}

	{

		ret := ""
		if len(r.Form["callback"]) > 0 {
			ret += r.Form["callback"][0]
		}
		ret += "(" + string(data) + ")"

		w.Write([]byte(ret))
		fmt.Println(string(ret))
		return
	}
	return
}


func saveJson(w http.ResponseWriter, r *http.Request) {

	fmt.Println("wx path", strings.Join([]string{"http://", r.Host, r.RequestURI}, ""))

	r.ParseForm()

	if r.Form["data"] == nil {
		return
	}

	w.Header().Set("Content-type", "application/json")


	filename := defaultfile
	if len(r.Form["file"]) > 0 {
		filename = 	r.Form["file"][0]
	}

	data := r.Form["data"][0]
	ioutil.WriteFile(filename + ".json", []byte(data), os.ModePerm)

	//fmt.Println(data)


	ret := ""
	if len(r.Form["callback"]) > 0 {
		ret += r.Form["callback"][0]
	}

	ret += "(" + string("{}") + ")"
	w.Write([]byte(ret))
	fmt.Println(string(ret))
	return
}
